<?php
	class PostsController extends AppController{
		var $name = 'Posts';	
		var $helpers = array('Javascript','Html');
		var $components = array('Auth','Session');
				
		function index($postID = null){			
			$this->view = 'Theme';
			$this->theme = 'default';
			$this->set('title_for_layout', 'xxxx  Post Title');
			// find the post and its reponse.
			$post = $this->Post->find('first',
				array(
					'conditions'=>array('Post.id' =>$postID),
					'fields'=>array('Post.id', 'Post.title','Post.content', 'Post.blogs_id','Post.users_id','Post.response_count')
				)
			);
			if(!empty($post)){
				$post = $post['Post'] ;
				// find the blog of the post .
				$this->loadModel('Blog') ;
				$blog = $this->Blog->find('first',array(
					'conditions'=> array( 'Blog.id' =>$post['blogs_id'] ),
					'fields'=>array('Blog.id', 'Blog.title','Blog.pic','Blog.description','Blog.followed_count','Blog.themeName') 
				));
				//find top sixteen people who are following the blog.
				$this->loadModel('UsersBlog');
				$this->UsersBlog->unbindModel( array('belongsTo'=>array('Blog') ));
				$followed = $this->UsersBlog->find('all',array(
					'conditions'=>array('UsersBlog.blogs_id'=> $blog['Blog']['id'],'UsersBlog.status'=>'follow'),
					'fields'=>array('User.id','User.username','User.pic'),
					'limit'=> 16,
					'order'=>'UsersBlog.id desc'
				));
				if(!empty($followed)){
					foreach($followed as $key => $value){
						$followed[$key] = $value['User'] ;
					}
				}
				$this->set('blog',$blog['Blog']);
				$this->set('followed',$followed);
			}else{
				$this->set('blog',null);
				$this->set('followed',null);
			}
			
			
			$cookie = $this->Cookie->read('Auth.User');
			$userName = $cookie['username']; 
			$blogHosts[0]['username'] = $userName;
			$this->set('blogHosts',$blogHosts);
			$this->set('post',$post);
			$this->set('users',$followed);
		}
		/**
		 * 
		 * add a new post
		 */
		function add($postId = null){
			$this->pageTitle = 'Add Post';
			$email = $this->Auth->user('email');
			$this->loadModel('UsersBlog')	;
			$bloginfo = $this->UsersBlog->find( 'all',array(
					'conditions'=>array('User.email'=>$email ,'UsersBlog.status'=>'own') ,
					'fields' =>array('User.id','Blog.id','Blog.title') 
					)
			) ;
			$blog = array() ;
			$i = 0 ;
			foreach($bloginfo as $key => $value){
				$blog[$i] = $value['Blog'] ;
				++$i ;
			}
			$this->set('blog',$blog);
			
			$this->loadModel('User');
			if(!empty($this->data)){
				$email = $this->Auth->user('email');
				$userid = $this->User->find('first',
					array('conditions'=>array('User.email'=>$email),
						  'fields' =>array('id')
						)
				);
				$title = $this->data['Post']['Title'] ;
				$content = $this->data['Post']['content'] ;
				$excerpt =  substr($content,0,300);
				$blogID = $this->data['Post']['Post to'] ;
				$post_time = $this->data['Post']['post_time'] ;
				$source_url = $this->data['Post']['source_url'] ;
				$custome_url = $this->data['Post']['custom_url'] ;
				$status = $this->data['Post']['Publish'] ;
				$users_id =	$userid['User']['id'] ;
				//save the post
				$error = $this->Post->save(array(
					'Post'=>array(
						'title'=>$title ,
						'content'=>$content ,
						'excerpt' => $excerpt ,
						'post_time'=>$post_time ,
						'source_url'=>$source_url ,
						'coustome_ulr'=>$custome_url ,
						'status' =>$status ,
						'blogs_id'=>$blogID ,
						'users_id'=>$users_id,
					)
				));
				if($error){
				//save the tags of the post .
						$tags = $this->data['Post']['tags'] ;
						// Find the tags of the post in the tag table .if it exsit ,get its id .If not, save it 
						//and get the new tag's id .
						if(!empty($tags)){
							$this->loadModel('PostHasTag');
							$this->loadModel('Tag');
							$tagArray = explode(",",$tags);
							foreach($tagArray as $key1 => $value1 ){
								$result = $this->Tag->find('first',array(
									'conditions' =>array('Tag.name'=>$value1),
									'fields'=>array('Tag.id')));
								$tagID = null ;
								if(empty($result)){
									$this->Tag->id = null ;
									if($this->Tag->save(array(
										'Tag'=> array('name' =>$value1 )))){
										$tagID = $this->Tag->id ;
									}else{
										$tagID = 1 ;//default tag
									}
								}else{
									$tagID = $result['Tag']['id'] ;
								}
								// save the the post's tag.
								$this->PostHasTag->id = null ;
								$this->PostHasTag->save(array(
										'PostHasTag'=>array(
											'posts_id'=> $this->Post->id,
											'tags_id'=>$tagID )
								));
							}
						}
					 $this->Session->setFlash('Your post has been saved.');
					 $this->redirect(array('action'=>'index',$this->Post->id));
				}
			}
			
		}
		/**
		 *
		 *Update posts
		 */
		function update($postID = null){
			// find the post and its reponse count.
			$post = $this->Post->find('first',
				array(
					'conditions'=>array('Post.id' =>$postID),
					'fields'=>array('Post.id', 'Post.title','Post.content', 'Post.blogs_id','Post.users_id','Post.source_url','Post.custom_url','Post.post_time')
				)
			);
			$this->loadModel('PostHasTag');
			$this->loadModel('User');
			$this->PostHasTag->unBindModel(array('belongsTo'=>array('Post')));
			$tags = $this->PostHasTag->find('all',array(
			 		'conditions'=>array('PostHasTag.posts_id'=>$postID),
			 		'fields'=>array('Tag.id' ,'Tag.name')
			 	));
			$this->set('post',$post['Post']);
			$this->set('tags',$tags);
			// update the post .
			if(!empty($this->data)){
				$email = $this->Auth->user('email');
				$userid = $this->User->find('first',
					array('conditions'=>array('User.email'=>$email),
						  'fields' =>array('id')
						)
				);
				$title = $this->data['Post']['Title'] ;
				$content = $this->data['Post']['content'] ;
				$excerpt =  substr($content,0,300);
				$post_time = $this->data['Post']['post_time'] ;
				$source_url = $this->data['Post']['source_url'] ;
				$custome_url = $this->data['Post']['custom_url'] ;
				$status = $this->data['Post']['Publish'] ;
				$users_id =	$userid['User']['id'] ;
				//save the post
				$this->Post->id = $this->data['Post']['postID'];
				$error = $this->Post->save(array(
					'Post'=>array(
						'title'=>$title ,
						'content'=>$content ,
						'excerpt' => $excerpt ,
						'post_time'=>$post_time ,
						'source_url'=>$source_url ,
						'coustome_ulr'=>$custome_url ,
						'status' =>$status ,
						'users_id'=>$users_id,
					)
				));
				// if post save successfully!
				// delete the old relation between posts and tags in the posts_has_tags table in the database.
				$this->PostHasTag->deleteAll(array(
						'PostHasTag.posts_id'=>$this->data['Post']['postID']
				),false);
				//
				if($error){
				//save the tags of the post .
						$tags = $this->data['Post']['tags'] ;
						// Find the tags of the post in the tag table .if it exsit ,get its id .If not, save it 
						//and get the new tag's id .
						if(!empty($tags)){
							$this->loadModel('PostHasTag');
							$this->loadModel('Tag');
							$tagArray = explode(",",$tags);
							// find the tags in the tag table
							foreach($tagArray as $key => $value ){
								// find if the tag has exsited in the table.
								$result = $this->Tag->find('first',array('conditions' =>array('Tag.name'=>$value)));
								$tagID = null ;
								if(empty($result)){
									// if the tag doesn't exist in the tag table.
									$this->Tag->id = null ;
									if($this->Tag->save(array('Tag'=>
										array('name' =>$value )))
									){
										$tagID = $this->Tag->id ;
									}// we ignore if it save falied.
								}else{
									$tagID = $result['Tag']['id'] ;
								}
								// now have the tag'id ,wo wanna save the relations of tags and the post
								$this->PostHasTag->id = null ;
								$this->PostHasTag->save(array(
										'PostHasTag'=>array(
											'posts_id'=> $this->Post->id,
											'tags_id'=>$tagID
										)
								));
							}
						}
					 $this->Session->setFlash('Your post has been saved.');
					 $this->redirect(array('action'=>'index',$this->Post->id));
				}
			}
		}
		
		function reblog($postID = null ){
			// find the current user's blogs.
			$email = $this->Auth->user('email');
			$this->loadModel('UsersBlog')	;
			$bloginfo = $this->UsersBlog->find( 'all',array(
					'conditions'=>array('User.email'=>$email ,'UsersBlog.status'=>'own') ,
					'fields' =>array('User.id','Blog.id','Blog.title') 
					)
			) ;
			$blog = array() ;
			$i = 0 ;
			foreach($bloginfo as $key => $value){
				$blog[$i] = $value['Blog'] ;
				++$i ;
			}
			$this->set('blog',$blog);
			// find the post and its reponse count.
			$post = $this->Post->find('first',
				array(
					'conditions'=>array('Post.id' =>$postID),
					'fields'=>array('Post.id', 'Post.title','Post.content', 'Post.blogs_id','Post.users_id','Post.source_url',
					'Post.custom_url','Post.post_time','Post.reblog_posts_id','Post.reblog_blog_title')
				)
			);
			$this->loadModel('PostHasTag');
			$this->loadModel('User');
			$this->PostHasTag->unBindModel(array('belongsTo'=>array('Post')));
			$tags = $this->PostHasTag->find('all',array(
			 		'conditions'=>array('PostHasTag.posts_id'=>$postID),
			 		'fields'=>array('Tag.id' ,'Tag.name')
			 	));
			$this->set('post',$post['Post']);
			$this->set('tags',$tags);
			// save the reblog post .
			if(!empty($this->data)){
				// the post informations.
				if(!empty($this->data['Post']['reblog_posts_id'])){
					// if there is reblog_posts_id, find the original original post .
					$postsInfo = $this->Post->find('first',array(
						'conditions'=>array('Post.id'=>$this->data['Post']['reblog_posts_id']),
						'fields'=>array('Post.id','Post.response_count')
					));
					// update the responsecout.
					if(!empty($postsInfo)){
						$this->Post->updateAll(array('response_count'=>$postsInfo['Post']['response_count'] + 1),array('id'=>$postsInfo['Post']['id']));//save the fields successfully.
						$this->Post->id = null  ;
					}
				}else{
					$postsInfo = $this->Post->find('first',array(
						'conditions'=>array('Post.id'=>$this->data['Post']['postID']),
						'fields'=>array('Post.id','Post.response_count')
					));
					// update the response_count .
					if(!empty($postsInfo)){
						$this->Post->updateAll(array('response_count'=>$postsInfo['Post']['response_count'] + 1),array('id'=>$postsInfo['Post']['id']));//save the fields successfully.
						$this->Post->id = null  ;
					}
				}
				$title = $this->data['Post']['Title'] ;
				$content = $this->data['Post']['content'] ;
				$excerpt =  substr($content,0,300);
				$blogID = $this->data['Post']['Post to'] ;
				$post_time = $this->data['Post']['post_time'] ;
				$source_url = $this->data['Post']['source_url'] ;
				$custome_url = $this->data['Post']['custom_url'] ;
				$status = $this->data['Post']['Publish'] ;
				$users_id =	$this->Auth->user('id') ;
				if(empty($this->data['Post']['reblog_posts_id']))
					$reblog_posts_id = $this->data['Post']['postID'] ;
				else 
					$reblog_posts_id = $this->data['Post']['reblog_posts_id'] ;
				$reblog_blogs_id = $this->data['Post']['blogs_id'] ;
				$this->loadModel('Blog');
				$reblogInfo['Blod']['title'] = null ;
				$reblogInfo = $this->Blog->find('first',array(
					'conditions'=>array('Blog.id'=>$reblog_blogs_id),
					'fields'=>array('Blog.title')
				));
				$reblog_blogs_title = $reblogInfo['Blog']['title'] ;
				//save the post
				$savePost = $this->Post->save(array(
					'Post'=>array(
						'title'=>$title ,
						'content'=>$content ,
						'excerpt' => $excerpt ,
						'post_time'=>$post_time ,
						'source_url'=>$source_url ,
						'coustome_ulr'=>$custome_url ,
						'status' =>$status ,
						'blogs_id'=>$blogID ,
						'reblog_posts_id'=>$reblog_posts_id,
						'reblog_blog_title'=>$reblog_blogs_title,
						'users_id'=>$users_id,
					)
				));
				// if save post succusfully , we save the response.
				$this->loadModel('Response');
				$this->Response->id = null ;
				$response_posts_id = null ;
				if(!empty($this->data['Post']['reblog_posts_id'])){
					$response_posts_id = $this->data['Post']['reblog_posts_id'] ;
				}else{
					$response_posts_id = $this->data['Post']['postID'] ;
				}
				$saveRes = $this->Response->save(array(
						'Response'=>array(
							'date'=>'now()',
							'type'=>'reblogged',
							'users_id'=>$users_id ,
							'posts_id'=>$response_posts_id
						)
					)
				);
				// if save the post sucussfully.
				if($savePost && $saveRes ){
				// upload the post's responese_count
				
				//save the tags of the post .
						$tags = $this->data['Post']['tags'] ;
						// Find the tags of the post in the tag table .if it exsit ,get its id .If not, save it 
						//and get the new tag's id .
						if(!empty($tags)){
							$this->loadModel('PostHasTag');
							$this->loadModel('Tag');
							$tagArray = explode(",",$tags);
							foreach($tagArray as $key1 => $value1 ){
								$result = $this->Tag->find('first',array(
									'conditions' =>array('Tag.name'=>$value1),
									'fields'=>array('Tag.id')));
								$tagID = null ;
								if(empty($result)){
									$this->Tag->id = null ;
									if($this->Tag->save(array(
										'Tag'=> array('name' =>$value1 )))){
										$tagID = $this->Tag->id ;
									}else{
										$tagID = 1 ;//default tag
									}
								}else{
									$tagID = $result['Tag']['id'] ;
								}
								// save the the post's tag.
								$this->PostHasTag->id = null ;
								$this->PostHasTag->save(array(
										'PostHasTag'=>array(
											'posts_id'=> $this->Post->id,
											'tags_id'=>$tagID )
								));
							}
						}
					 $this->Session->setFlash('Your post has been saved.');
					 $this->redirect(array('action'=>'index',$this->Post->id));
				}
			}
		}
		/**
		 *
		 *Update posts
		 */
		function response(){
			
		}
		/**
		function test(){
			$this->autoRender = false;
			$this->layout = null;
			$content = $_REQUEST['test'];
			return $content;
		}
		**/
	}
?>